<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Carbon;
use App\Models\OpenapiLog;

class DfacService
{
    protected $host;

    public function __construct()
    {
        $this->host = config('dfac.host');
    }

    public function givePointToReferee($unionid, $action, $point)
    {
        $url = $this->host . '/openapi/customAction';
        $params = [
            'unionid' => $unionid,
            'action' => $action,
            'point' => $point
        ];
        $params = $this->setParams($params);

        $response = Http::post($url, $params);
        $result = $response->json();
        OpenapiLog::addLog($url, $params, $result, 'post');
        if (isset($result['errcode']) && $result['errcode'] == 0) {
            return true;
        } else {
            $message = isset($result['message']) ? $result['message'] : '卡友E家接口异常';
            throw_invalid_request_exception(null, [], $message);
        }
    }

    public function getCustomerInfo($unionid)
    {
        $url = $this->host . '/openapi/customer';
        $params = [
            'unionid' => $unionid,
        ];
        $params = $this->setParams($params);

        $response = Http::get($url, $params);
        $result = $response->json();
        OpenapiLog::addLog($url, $params, $result, 'get');
        if (isset($result['errcode']) && in_array($result['errcode'], [0, 1201])) {
            return $result;
        } else {
            $message = isset($result['message']) ? $result['message'] : '卡友E家接口异常';
            throw_invalid_request_exception(null, [], $message);
        }
    }

    public function setParams($params)
    {
        $params['datetime'] = Carbon::now()->toDateTimeString();
        $params['key'] = config('dfac.secret_key');
        ksort($params);
        $json = json_encode($params);
        $params['secret_key'] = md5($json);
        return $params;
    }
}
